package com.ruoyi.lvlian.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.MD5Utils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.Seq;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.BusinessLicenseInfo;
import com.ruoyi.lvlian.domain.BusinessLicenseInfoLabel;
import com.ruoyi.lvlian.domain.SysOrganizationDomain;
import com.ruoyi.lvlian.dto.BusinessLicenseInfoDto;
import com.ruoyi.lvlian.mapper.BusinessLicenseInfoMapper;
import com.ruoyi.lvlian.service.IBusinessLicenseInfoService;
import com.ruoyi.lvlian.util.ExcelUtil;
import com.ruoyi.lvlian.vo.IdCardInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 主体基本信息Service业务层处理
 *
 * @author lvlian
 * @date 2024-07-24
 */
@Service
public class BusinessLicenseInfoServiceImpl implements IBusinessLicenseInfoService {
    @Autowired
    private BusinessLicenseInfoMapper businessLicenseInfoMapper;

    /**
     * 查询主体基本信息
     *
     * @param id 主体基本信息主键
     * @return 主体基本信息
     */
    @Override
    public BusinessLicenseInfo selectBusinessLicenseInfoById(String id) {
        return businessLicenseInfoMapper.selectBusinessLicenseInfoById(id);
    }

    /**
     * 查询主体基本信息列表
     *
     * @param businessLicenseInfo 主体基本信息
     * @return 主体基本信息
     */
    @Override
    public List<BusinessLicenseInfo> selectBusinessLicenseInfoList(BusinessLicenseInfoDto businessLicenseInfo) {
        return businessLicenseInfoMapper.selectBusinessLicenseInfoList(businessLicenseInfo);
    }

    /**
     * 新增主体基本信息
     *
     * @param businessLicenseInfo 主体基本信息
     * @return 结果
     */
    @Override
    public int insertBusinessLicenseInfo(BusinessLicenseInfo businessLicenseInfo) {
        businessLicenseInfo.setId(MD5Utils.md5(businessLicenseInfo.getCompanyCode() + businessLicenseInfo.getSubjectRole() + businessLicenseInfo.getSubjectRole() + businessLicenseInfo.getDataSource()));
        businessLicenseInfo.setCreateUser(SecurityUtils.getUsername());
        businessLicenseInfo.setCreateDate(DateUtils.getCurrentTime());
        if (StringUtils.isEmpty(businessLicenseInfo.getSubjectRole())) {
            businessLicenseInfo.setSubjectRole("供应商(自然人)");
        }
        return businessLicenseInfoMapper.insertBusinessLicenseInfo(businessLicenseInfo);
    }

    /**
     * 修改主体基本信息
     *
     * @param businessLicenseInfo 主体基本信息
     * @return 结果
     */
    @Override
    public int updateBusinessLicenseInfo(BusinessLicenseInfo businessLicenseInfo) {
        businessLicenseInfo.setCreateUser(SecurityUtils.getUsername());
        businessLicenseInfo.setCreateDate(DateUtils.getCurrentTime());
        if (StringUtils.isEmpty(businessLicenseInfo.getSubjectType())) {
            businessLicenseInfo.setSubjectType("企业");
        }
        if ("账本".equalsIgnoreCase(businessLicenseInfo.getSubjectRole())) {
            SysOrganizationDomain dom = new SysOrganizationDomain();
            dom.setCategory("4");
            dom.setParentId(businessLicenseInfo.getDomainParentId());
            dom.setParentName(businessLicenseInfo.getDomainParentName());
            dom.setLabel(businessLicenseInfo.getCompanyName());
            dom.setCode(businessLicenseInfo.getOrgCode());
            dom.setCreatedAt(new Date());
            dom.setCreateUser(SecurityUtils.getUsername());
            dom.setId(MD5Utils.md5(dom.getLabel() + dom.getCode() + dom.getParentId()));
            businessLicenseInfoMapper.insertSysOrganizationDomain(dom);
        }
        if (StringUtils.isEmpty(businessLicenseInfo.getId())) {
            return this.insertBusinessLicenseInfo(businessLicenseInfo);
        }

        if (StringUtils.isNotEmpty(businessLicenseInfo.getIdCardImg())) {
            businessLicenseInfo.setCompanyImg(businessLicenseInfo.getIdCardImg());
        }
        businessLicenseInfo.setStatus("true");
        if (null == businessLicenseInfo.getIdNum() || 5 > businessLicenseInfo.getIdNum().length()) {
            businessLicenseInfo.setIdNum(Seq.getId());
        }
        int updateResult = businessLicenseInfoMapper.updateLvBusinessLicenseInfo(businessLicenseInfo);
        if (0 == updateResult) {
            updateResult = this.insertBusinessLicenseInfo(businessLicenseInfo);
        }

        if ("自然人".equalsIgnoreCase(businessLicenseInfo.getSubjectType())) {
            //        如果是自然人，那么就要更新身份证信息表。

            boolean flag = businessLicenseInfoMapper.findCardInfoExist(businessLicenseInfo.getIdNum());
            IdCardInfo idCardInfo = new IdCardInfo();
            idCardInfo.setId(MD5Utils.md5(businessLicenseInfo.getIdNum()));
            idCardInfo.setCreateUser(SecurityUtils.getUsername());
            idCardInfo.setCreateDate(DateUtils.getCurrentTime());
            idCardInfo.setIdCard(businessLicenseInfo.getIdNum());
            idCardInfo.setIdCardImg(businessLicenseInfo.getCompanyImg());
            idCardInfo.setName(businessLicenseInfo.getCompanyName());
            try {
                if (flag) {
                    businessLicenseInfoMapper.updateIdCardInfo(idCardInfo);
                } else {
                    businessLicenseInfoMapper.insertIdCardInfo(idCardInfo);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }


        return updateResult;


    }

    /**
     * 批量删除主体基本信息
     *
     * @param ids 需要删除的主体基本信息主键
     * @return 结果
     */
    @Override
    public int deleteBusinessLicenseInfoByIds(String[] ids) {
        return businessLicenseInfoMapper.deleteBusinessLicenseInfoByIds(ids);
    }

    /**
     * 删除主体基本信息信息
     *
     * @param id 主体基本信息主键
     * @return 结果
     */
    @Override
    public int deleteBusinessLicenseInfoById(String id) {
        return businessLicenseInfoMapper.deleteBusinessLicenseInfoById(id);
    }

    @Override
    public List<BusinessLicenseInfo> importInfoEnterprise(MultipartFile file, String sheetName, int rowNum) throws Exception {
        byte[] fileBytes = file.getBytes();
        List<BusinessLicenseInfo> invoiceRecyclingInfos = ExcelUtil.readExcel(fileBytes, BusinessLicenseInfo.class, sheetName, rowNum);
        for (BusinessLicenseInfo po : invoiceRecyclingInfos) {
            po.setSubjectRole(sheetName);
        }
        return invoiceRecyclingInfos;
    }

    @Override
    public int bachSave(List<BusinessLicenseInfo> dtoList) {
        int saveBatch = 0;
        List<BusinessLicenseInfo> newList = new ArrayList<>();
        if (!dtoList.isEmpty()) {
            for (BusinessLicenseInfo po : dtoList) {

                if (StringUtils.isNotEmpty(po.getCompanyCode()) || StringUtils.isNotEmpty(po.getIdNum())) {
                    String id = MD5Utils.md5(po.getCompanyCode() + po.getSubjectRole() + po.getSubjectRole() + po.getDataSource());
                    if ("自然人".equalsIgnoreCase(po.getSubjectType())) {
                        id = MD5Utils.md5(po.getIdNum() + po.getSubjectRole() + po.getSubjectRole() + po.getDataSource());
                    }

                    po.setDataSource("四流平台");

                    po.setId(id);
                    po.setSubjectNum(po.getCompanyCode());

                    po.setCreateUser(SecurityUtils.getUsername());
                    po.setCreateDate(DateUtils.getCurrentTime());
                    newList.add(po);
                }
            }


            String[] arr = newList.stream()
                    .map(BusinessLicenseInfo::getId)
                    .distinct()
                    .toArray(String[]::new);
            //             导入之前 先删除
            businessLicenseInfoMapper.batchDelete(arr);
            saveBatch = businessLicenseInfoMapper.batchSave(newList);

        }
        return saveBatch;
    }


    @Override
    public List<BusinessLicenseInfoLabel> queryAccountList(BusinessLicenseInfoDto businessLicenseInfo) {

        return businessLicenseInfoMapper.queryAccountList(businessLicenseInfo);
    }

    @Override
    public BusinessLicenseInfo selectBusinessLicenseInfoByName(String name) {
        BusinessLicenseInfo vo = businessLicenseInfoMapper.selectBusinessLicenseInfoByName(name);
        return vo;
    }

    @Override
    public BusinessLicenseInfo selectBusinessLicenseInfoByOrgCode(String orgCode) {
        return businessLicenseInfoMapper.selectBusinessLicenseInfoByOrgCode(orgCode);
    }

    @Override
    public List<BusinessLicenseInfoLabel> queryAllAccountList(BusinessLicenseInfoDto businessLicenseInfo) {
        return businessLicenseInfoMapper.queryAccountList(businessLicenseInfo);
    }

}
